package com.itheima.appserver.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.HuanXinConfig;
import com.itheima.appserver.exception.MyException;
import com.itheima.appserver.exception.ResultError;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.appserver.service.UserService;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.HuanxinUser;
import com.itheima.commons.pojo.User;
import com.itheima.interfaces.HuanXinApi;
import com.itheima.interfaces.UserApi;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinConfig config;

    @Reference
    private UserApi userAPI;

    @Reference
    private HuanXinApi huanXinAPI;

    @Override
    public void userSendLoginMsg(String phone) {
        //判断手机号格式是否正确
        if (!Validator.isMobile(phone)) {
            throw new MyException(ResultError.phoneError());
        }
        //判断验证码是否过期
        String phoneCode = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (!StrUtil.isBlank(phoneCode)) {
            throw new MyException(ResultError.sendCodeError());
        }

       /* //随机生成验证码
        String randomNumbers = RandomUtil.randomNumbers(6);
        System.out.println(randomNumbers);

        //发送验证码
        Boolean sendSMS = SendSMSUtil.sendSMS(phone, randomNumbers, Constants.SMS_CODE);
        if (!sendSMS){
            throw new MyException(ResultError.sendSMSError());

        }*/
        String randomNumbers = "123456";
        //把验证码存入redis
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, randomNumbers, 5, TimeUnit.MINUTES);

    }

    @Override
    public HashMap<String, Object> userLoginVerification(Map<String, String> map) {
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");
        //判断手机号格式是否正确
        if (Validator.isMobile(map.get(phone))) {
            throw new MyException(ResultError.phoneError());
        }
        //从redis中拿出验证码进行判断
        String phoneCode = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (verificationCode == null || phoneCode == null || !phoneCode.equals(verificationCode)) {
            throw new MyException(ResultError.codeError());
        }
        //删除验证码
        redisTemplate.delete(Constants.SMS_CODE + phone);

        //都正确 判断 是否是新用户
        User user = userAPI.selectUserByPhone(phone);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("isNew", false);
        if (user == null) {
            //新用户
            user = userAPI.addUser(User.builder()
                    .mobile(phone)
                    .password(Constants.INIT_PASSWORD)
                    .created(new Date())
                    .updated(new Date())
                    .build());
            hashMap.put("isNew", true);

            HttpResponse response = requestService.execute(config.getUrl() + config.getOrgName() + "/" + config.getAppName() + "/users", JSONUtil.createObj()
                            .set("username", "HX_" + user.getId())
                            .set("password", SecureUtil.md5(user.getMobile())).toString()
                    , Method.POST);
            if (!response.isOk()) {
                throw new MyException(ResultError.userRegitError());
            }

            HuanxinUser huanXin = new HuanxinUser();
            huanXin.setUsername("HX_" + user.getId());
            huanXin.setPassword(SecureUtil.md5(user.getMobile()));
            huanXin.setNickname(null);
            huanXin.setUserId(user.getId());
            huanXin.setCreated(new Date());
            huanXin.setUpdated(new Date());
            huanXinAPI.save(huanXin);


        }


//        //添加用户登录信息
//        UserLogin userLogin = new UserLogin();
//        userLogin.setUserId(userEntity.getId());
//        userLogin.setLoginTime(new Date());
//        userLogin.setOutTime(DateUtils.addHours(new Date(), 1));
//        userLoginService.addUserLogin(userLogin);
//
//        //是否解冻
//        UserFreeze userFreeze = userFreezeService.findByUid(userEntity.getId());
//        if (userFreeze.getThawTime().getTime() <= System.currentTimeMillis()) {
//            userFreezeService.deleteUserFreezeByUid(userEntity.getId());
//        } else {
//            throw new MyException(new ErrorResult(ResultCode.USER_REGIT_ERROR));
//        }

        //第一次注册的时候定义接收语音次数
        int count = 10;
        redisTemplate.opsForValue().set(Constants.SOUND + user.getId().toString(), String.valueOf(count));
        //生成token
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", user.getId());
        payload.put("phone", user.getMobile());
        payload.put("expire_time", DateTime.of(System.currentTimeMillis() + Constants.JWT_TIME_OUT));
        String token = JWTUtil.createToken(payload, Constants.JWT_SECRET.getBytes());
        hashMap.put("token", token);
        //设置注册时默认为初级为锁定状态0 中级和高级为锁定状态1
      /*  redisTemplate.opsForList().set(Constants.QUESTIONNAIRE + user.getId(),0,"0");
        redisTemplate.opsForList().set(Constants.QUESTIONNAIRE + user.getId(),1,"1");
        redisTemplate.opsForList().set(Constants.QUESTIONNAIRE + user.getId(),2,"1");
        Long size = redisTemplate.opsForList().size(Constants.QUESTIONNAIRE + user.getId());
        System.out.println(size);*/
        return hashMap;
    }
}
